package com.ruoyi.outpatient.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.PersonConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.outpatient.core.LoginPatient;
import com.ruoyi.outpatient.domain.Person;
import com.ruoyi.outpatient.mapper.IPersonLoginMapper;
import com.ruoyi.outpatient.service.IPersonLoginService;
import com.ruoyi.outpatient.service.patient.impl.PatientTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.token.TokenService;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class PersonLoginServiceImpl implements IPersonLoginService {


    @Autowired
    private IPersonLoginMapper personLoginMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private PatientTokenService tokenService;

    @Autowired
    private AuthenticationManager authenticationManager;


    /**
     *  验证码账户登录
     * @param phonenumber 手机号
     * @return token
     */
    @Override
    public String verifyLogin(String phonenumber) {





//        3.直接查数据库,不用redis
        Person person=personLoginMapper.selectPersion(phonenumber);




//        4.数据库存在则 对象存入redis的hash
        if (StringUtils.isNotNull(person)){
            Map<String, Object> map = BeanUtil.beanToMap(person);
            redisCache.setCacheMap(PersonConstants.PERSON_INFORMATION+person.getPersonId(),map);
//            个人资料30天在redis过期
            redisCache.expire(PersonConstants.PERSON_INFORMATION+person.getPersonId(), Constants.INFORMATION_EXPIRATION, TimeUnit.DAYS);

//            生成token返回
            LoginPatient loginPatient=new LoginPatient();
            loginPatient.setPerson(person);
            //存到redis并生成token
            String token = tokenService.createToken(loginPatient);



            //        统计一下活跃用户登录天数
            String today= DateUtil.today(); //2022-55-05
            String[] split = today.split("-");      //(sign:3:2022:05,23,true)
            redisCache.setBig("signActiveUser:"+person.getPersonId()+":"+split[0]+":"+split[1],Long.valueOf(split[2]).longValue()-1,true);

            return token;
        }

//        5.如果数据库不存在,则是第一次登录,需要存入数据然后返回token
        person.setPersonName("用户"+RandomUtil.randomNumbers(5));
        person.setPhonenumberPassword("123456");
        person.setPhonenumber(phonenumber);
        person.setIdentNumber(RandomUtil.randomNumbers(9)); //随机生成9位小蓝书号
        person.setSex(PersonConstants.SEX);
        person.setAvatar("https://weifeng-book.oss-cn-shenzhen.aliyuncs.com/2022-05-24/ddc90bc8-9c18-4991-a121-a5528892257f%E5%9B%BE%E7%89%87.jpg");
//        插入数据
        personLoginMapper.insertPerson(person);

//        生成token 返回
        LoginPatient loginPatient=new LoginPatient();
        loginPatient.setPerson(person);
        //存到redis并生成token
        String token = tokenService.createToken(loginPatient);




//        统计一下活跃用户登录天数
        String today= DateUtil.today(); //2022-55-05
        String[] split = today.split("-");      //(sign:3:2022:05,23,true)
        redisCache.setBig("signActiveUser:"+person.getPersonId()+":"+split[0]+":"+split[1],Long.valueOf(split[2]).longValue()-1,true);

        return token;
    }


    /**
     * 手机密码登录
     * @param phonenumber 手机号
     * @param password 密码
     * @return token
     */
    @Override
    public String passwordLogin(String phonenumber, String password) {


//        将手机号和密码交给security容器
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(phonenumber,password);
        Authentication authentication =authenticationManager.authenticate(authenticationToken);


//        将认证后的数据封装到userdetail
        LoginPatient loginPatient=(LoginPatient) authentication.getPrincipal();
//        生成token
        String token = tokenService.createToken(loginPatient);




        //        统计一下活跃用户登录天数
        String today= DateUtil.today(); //2022-55-05
        String[] split = today.split("-");      //(sign:3:2022:05,23,true)
        redisCache.setBig("signActiveUser:"+loginPatient.getPerson().getPersonId()+":"+split[0]+":"+split[1],Long.valueOf(split[2]).longValue()-1,true);

        return token;
    }


}
